package com.qire.manhua.model.viewModel.impl;

import android.graphics.Color;
import android.graphics.Paint;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.activity.AccountsAssociatedActivity;
import com.qire.manhua.controller.AccountsAssociatedController;
import com.qire.manhua.dal.service.AccountsAssociatedService;
import com.qire.manhua.databinding.LayoutAccountsAssociatedItemBinding;
import com.qire.manhua.view.style.RadiusBackgroundSpan;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;

public class AccountsAssociatedViewModel extends BaseViewModel<IViewModel> implements IViewModel {

    private AccountsAssociatedService associatedService = new AccountsAssociatedService(this);

    private final ArrayList<AccountsAssociatedItemViewModel> accountInfoList = new ArrayList<>();
    private final SummerBindAdapter accountAdapter = new SummerBindAdapter(accountInfoList);

    private AccountsAssociatedItemViewModel accountInfo;

    @Override
    public int getVariableId() {
        return BR.accountsAssociatedViewModel;
    }

    //region    #附加管理 begin

    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(AccountsAssociatedController controller) {
        this.accountAdapter.setEventProcess(controller);
        refreshAccountInfoUI();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.associatedService = null;
        this.accountAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务及数据 begin
    public void loadAccountRelatedInfo() {
        clearAccountInfoList();
        associatedService.loadAccountRelatedInfo();
    }

    public void clearAccountInfoList() {
        accountInfoList.clear();
    }

    public void addAccountsAssociatedItem(int index, int userId, String userName, String lastLoginTime, String userHash,
                                          String userImg, String coin, String bean, boolean isVip) {
        accountInfoList.add(new AccountsAssociatedItemViewModel(index, userId, userName, lastLoginTime, userHash, userImg, coin, bean, isVip));
    }

    public void refreshAccountAdapter() {
        accountAdapter.notifyDataSetChanged();
        if(ListUtil.notEmpty(accountInfoList)) {
            accountInfoList.get(0).toggle();
        } else {
            refreshAccountInfoUI();
        }
    }

    public void toggleLoginAccount() {
        if(ObjectUtil.nonNull(accountInfo)) {
            associatedService.toggleLoginAccount(accountInfo.userId, accountInfo.userHash, AccountsAssociatedActivity.class.getSimpleName());
        } else {
            ToastHelper.showToast("请选择期望切换的账户！");
        }
    }

    private void toggleAccountInfo(AccountsAssociatedItemViewModel newAccountInfo) {
        if(ObjectUtil.nonNull(accountInfo)) {
            accountInfo.setCheck(false);
        }

        newAccountInfo.setCheck(true);

        accountInfo = newAccountInfo;
        refreshAccountInfoUI();
    }

    //endregion #业务及数据 end

    //region    #UI操作 begin
    public void refreshAccountInfoUI() {
        boolean haveAccount = ObjectUtil.nonNull(accountInfo);
        set("accountInfo", accountInfo);
        set("accountInfoVisible", haveAccount ? View.VISIBLE : View.GONE);
        set("loginAccountBtnVisible", (haveAccount && accountInfo.notLoginAccount()) ? View.VISIBLE : View.GONE);
    }
    //endregion #UI操作 end

    //region    #UI绑定 begin

    public MutableLiveData<Integer> getAccountInfoVisible() {
        return get("accountInfoVisible");
    }

    public MutableLiveData<Integer> getLoginAccountBtnVisible() {
        return get("loginAccountBtnVisible");
    }

    public MutableLiveData<AccountsAssociatedItemViewModel> getAccountInfo() {
        return get("accountInfo");
    }

    public BaseAdapter getAccountAdapter() {
        return accountAdapter;
    }

    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_accounts_associated_item)
    public class AccountsAssociatedItemViewModel extends BaseObservable implements AutoVariable<LayoutAccountsAssociatedItemBinding> {

        private final int       index;
        private final int       userId;
        private final String    userName;
        private final String    lastLoginTime;
        private final String    userHash;
        private final String    userImg;
        private final String    coin;
        private final String    bean;
        private final boolean   isVip;

        private boolean isCheck = false;

        public AccountsAssociatedItemViewModel(int index, int userId, String userName, String lastLoginTime, String userHash,
                                               String userImg, String coin, String bean, boolean isVip) {
            this.index          = index;
            this.userId         = userId;
            this.userName       = userName;
            this.lastLoginTime  = lastLoginTime;
            this.userHash       = userHash;
            this.userImg        = userImg;
            this.coin           = coin;
            this.bean           = bean;
            this.isVip          = isVip;
        }

        public int userId() {
            return userId;
        }

        public String userHash() {
            return userHash;
        }

        public boolean notLoginAccount() {
            return index > 1;
        }

        public void setCheck(boolean isCheck) {
            this.isCheck = isCheck;
            notifyPropertyChanged(BR.itemModuleBgRid);
        }

        public void toggle() {
            if(!isCheck) {
                toggleAccountInfo(this);
            }
        }

        @Override
        public void bindVariable(LayoutAccountsAssociatedItemBinding viewBind) {
            viewBind.setAccountsAssociatedItemViewModel(this);
        }

        @Bindable
        public int getItemModuleBgRid() {
            return isCheck ? R.drawable.app_accounts_associated_item_bg_a : R.drawable.app_accounts_associated_item_bg_b;
        }
        @Bindable
        public int getVipHeadWearVisible() {
            return this.isVip ? View.VISIBLE : View.GONE;
        }
        @Bindable
        public String getUserHeadImage() {
            return userImg;
        }
        @Bindable
        public CharSequence getUserNickname() {
            return userName;
        }
        @Bindable
        public int getTagsVisible() {
            return index <= 2 ? View.VISIBLE : View.GONE;
        }
        @Bindable
        public CharSequence getTags() {

            String label = notLoginAccount() ? "最近使用" : "已登录";
            int    bgColor = notLoginAccount() ? Color.rgb(0xFF, 0xf2, 0xe1) : Color.rgb(0xe4, 0xf7, 0xec);
            int    fgColor = notLoginAccount() ? Color.rgb(0xFF, 0x90, 0x00) : Color.rgb(0x1f, 0xb4, 0x54);

            SpannableStringBuilder builder = new SpannableStringBuilder();

            int startIndex = builder.length();
            builder.append(label + " ");
            RadiusBackgroundSpan bgSpan = new RadiusBackgroundSpan(bgColor, EquipmentInfoUtil.dip2px(4), Paint.Style.FILL_AND_STROKE);//25);
            ForegroundColorSpan fgSpan = new ForegroundColorSpan(fgColor);
            builder.setSpan(bgSpan, startIndex, startIndex + label.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(fgSpan, startIndex, startIndex + label.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            return builder;
        }
        @Bindable
        public CharSequence getUserId() {
            return "ID：" + userId;
        }
        @Bindable
        public CharSequence getLastLoginTime() {
            return "上次登录：" + lastLoginTime;
        }
        @Bindable
        public CharSequence getCoins() {
            return coin;
        }
        @Bindable
        public CharSequence getBeans() {
            return bean;
        }
    }

}
